/**************************************************************************************** 
 Copyright © 2003-2012 hbasesoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.hbasesoft.hamibot.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;
import com.hbasesoft.framework.common.utils.date.DateUtil;
import com.hbasesoft.framework.common.utils.logger.LoggerUtil;
import com.hbasesoft.hamibot.dao.AppConfigDao;
import com.hbasesoft.hamibot.entity.AppConfigEntity;
import com.hbasesoft.hamibot.vo.AppVo;

import jakarta.annotation.Resource;

/**
 * <Description> <br>
 * 
 * @author 王伟<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2024年12月23日 <br>
 * @since V1.0<br>
 * @see com.hbasesoft.hamibot.controller <br>
 */
@RestController
@RequestMapping("/api/config")
public class AppConfigController {

    /** 
     * 
     */
    @Resource
    private AppConfigDao appConfigDao;

    /**
     * Description: 查询 <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @return <br>
     */
    @Transactional(readOnly = true)
    @GetMapping
    public List<AppVo> query() {
        List<AppConfigEntity> list = appConfigDao
            .queryByLambda(q -> q.eq(AppConfigEntity::getIsDelete, 0).orderByDesc(AppConfigEntity::getUpdateTime));

        List<AppVo> appGroupList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, List<AppVo>> appList = list.stream().map(app -> {
                try {
                    AppVo vo = JSONObject.parseObject(app.getContent(), AppVo.class);
                    vo.setId(app.getId());
                    return vo;
                }
                catch (Exception e) {
                    LoggerUtil.error(e);
                }
                return null;
            }).filter(t -> t != null).sorted((t1, t2) -> t1.getSeq() - t2.getSeq())
                .collect(Collectors.groupingBy(AppVo::getGroupName));

            int i = -999;
            for (Entry<String, List<AppVo>> entry : appList.entrySet()) {
                if (entry.getValue().size() > 1) {
                    AppVo appGroup = new AppVo();
                    appGroup.setId(i++);
                    appGroup.setChildren(entry.getValue());
                    appGroup.setAppName(entry.getKey());
                    appGroupList.add(appGroup);
                }
                else {
                    appGroupList.add(entry.getValue().get(0));
                }
            }
        }
        return appGroupList;
    }

    /**
     * Description: 删除 <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @param id <br>
     */
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/{id}")
    public void del(final @PathVariable("id") Integer id) {
        appConfigDao.updateByLambda(q -> q.set(AppConfigEntity::getIsDelete, 1).set(AppConfigEntity::getDeleteBy, "系统")
            .set(AppConfigEntity::getDeleteTime, DateUtil.getCurrentDate()).eq(AppConfigEntity::getId, id));
    }

    /**
     * Description: <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @param vo <br>
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public void update(final @RequestBody AppVo vo) {
        AppConfigEntity entity = new AppConfigEntity();
        entity.setAppName(vo.getAppName());
        Integer id = vo.getId();
        vo.setId(null);
        String body = JSONObject.toJSONString(vo);
        entity.setContent(body);
        if (id == null) {
            entity.setCreateBy("系统");
            entity.setCreateTime(DateUtil.getCurrentDate());
            entity.setIsDelete(0);
            entity.setUpdateBy(entity.getCreateBy());
            entity.setUpdateTime(entity.getCreateTime());
            appConfigDao.save(entity);
        }
        else {
            appConfigDao.updateByLambda(q -> q.set(AppConfigEntity::getAppName, entity.getAppName())
                .set(AppConfigEntity::getContent, entity.getContent()).set(AppConfigEntity::getUpdateBy, "系统")
                .set(AppConfigEntity::getUpdateTime, DateUtil.getCurrentDate()).eq(AppConfigEntity::getId, id));
        }
    }
}
